package com.qiangesoft.wechat.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 微信接入控制器
 * ps:（JS接口安全域名、网页授权域名需要获取MP_verify_GEmwofiOtZ2hcL49.txt）
 * <a href="https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/function&action=function&token=854866943&lang=zh_CN">...</a>
 *
 * @author qiangesoft
 * @date 2023-09-11
 */
@Slf4j
@Api(tags = "微信接入")
@RestController
@RequestMapping("/wechat")
public class WxAccessController {


    /**
     * 获取安全凭证
     * ps:例如[http://主机:端口/wechat/MP_verify_GEmwofiOtZ2hcL49.txt]
     *
     * @param fileName
     * @param response
     */
    @ApiOperation(value = "安全凭证")
    @GetMapping("/{fileName}")
    public void security(@PathVariable String fileName, HttpServletResponse response) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 获取文件
            ClassPathResource classPathResource = new ClassPathResource(fileName);
            String filename = classPathResource.getFilename();
            is = classPathResource.getInputStream();
            byte[] bytes = is.readAllBytes();

            response.setCharacterEncoding("UTF-8");
            response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
            response.addHeader(HttpHeaders.CONTENT_LENGTH, bytes.length + "");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            os.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
